<?php
namespace gnomephp\input;
/**
 *
 * Deals with $_FILES data, filters the specific data with HTMLPurifier.
 * @author peec
 *
 */
class Files{

	private $data=array();

	/**
	 * Constructs the Files class, reorderes $_FILES array and makes it ready.
	 */
	public function __construct(){

		$this->data = $this->filterFiles($this->fixFilesArray($_FILES));
		
	}
	
	protected function fixFilesArray($files){
		if (isset($files['name'], $files['tmp_name'], $files['size'], $files['type'], $files['error']) && is_array($files['name']) && isset($files['name'][0])){
			foreach($files['name'] as $k => $v){
				$files[$k] = array(
					'name' => $files['name'][$k],
					'tmp_name' => $files['tmp_name'][$k],
					'size' => $files['size'][$k],
					'type' => $files['type'][$k],
					'error' => $files['error'][$k],
				);
			}
		}elseif(is_array($files)){
			foreach($files as $k => $v){
				$files[$k] = $this->fixFilesArray($v);
			}
		}else{
			return $files;
		}
		return $files;
	}
	
	
	/**
	 * Gets a upload object.
	 * @param string $key The name of the input field.
	 * @return UploadField
	 */
	public function get($key){
		return $this->data[$key];
	}
	/**
	 * Gets all the files posted.
	 * You can check if it's a UploadField or array with is_array.
	 * @param string $key The name of the input field.
	 * @return array
	 */
	public function getAllFiles(){
		return $this->data;
	}
	
	
	
	
	/**
	 * 
	 * Filters array of file data.
	 * @param mixed $postVars Files Vars / File var.
	 * @throws FilesException Should not throw this one, but if files data is corrupt it may do so.
	 */
	private function filterFiles($vars){
		
		if (is_array($vars) && !isset($vars['name'], $vars['tmp_name'], $vars['size'], $vars['type'], $vars['error'])){
			foreach($vars as $k => $v){
				$vars[$k] = $this->filterFiles($v);
			}
		}elseif (isset($vars['name'], $vars['tmp_name'], $vars['size'], $vars['type'], $vars['error'])){
			$vars = new UploadField($vars);
		}else{
			throw new FilesException("Internal FrameWork error, could not filter \$_FILES array.");
		}
		
		return $vars;
	}

	
	


}